<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">收货地址</h2>
        <el-button type="primary" @click="handleAdd">新增地址</el-button>
      </div>

      <!-- 地址列表 -->
      <div class="space-y-4">
        <el-empty v-if="!addresses.length" description="暂无收货地址" />

        <el-card
          v-for="address in addresses"
          :key="address.id"
          class="address-card hover:shadow-md transition-shadow"
        >
          <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div class="flex-1">
              <div class="flex flex-wrap items-center gap-2 mb-2">
                <span class="font-bold">{{ address.name }}</span>
                <span class="text-gray-600">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault" type="success" size="small">默认地址</el-tag>
              </div>
              <p class="text-gray-600">{{ address.address }}</p>
            </div>
            <div class="flex gap-2 sm:flex-col lg:flex-row">
              <el-button type="primary" link @click="handleEdit(address)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(address)">删除</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 地址表单对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑地址' : '新增地址'"
      width="90%"
      style="max-width: 600px"
      top="15vh"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="addressForm"
        :rules="rules"
        label-width="80px"
        class="address-form"
        @submit.prevent
      >
        <el-form-item label="收货人" prop="name">
          <el-input
            v-model="addressForm.name"
            placeholder="请输入收货人姓名"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="addressForm.phone"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择所在地区"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址，如街道、门牌号等"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import regionsData from '@/data/regions.json'
import {ElMessage, ElMessageBox} from "element-plus";
import {addOrUpdateAddress, deleteAddress, getAddresses} from "@/api/address.js";

const showDialog = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

onMounted(() => {
  initData()
})

const initData = () => {
  getAddresses().then(res => {
    addresses.value = res.data.map(item => {
      return {
        ...item,
        isDefault: Boolean(item.isDefault),
        address:`${item.region.join('')}${item.detail}`
      }
    })
  })
}
// 模拟地址数据
const addresses = ref([])

// 表单数据
const addressForm = reactive({
  name: '',
  phone: '',
  region: [],
  detail: '',
  isDefault: false
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

// 省市区数据
const regionOptions = regionsData.regions

// 新增地址
const handleAdd = () => {
  isEdit.value = false
  Object.assign(addressForm, {
    id: undefined,
    name: '',
    phone: '',
    region: [],
    detail: '',
    isDefault: false
  })
  showDialog.value = true
}

// 编辑地址
const handleEdit = (address) => {
  isEdit.value = true
  Object.assign(addressForm, {
    id: address.id,
    name: address.name,
    phone: address.phone,
    region: address.region,
    detail: address.detail,
    isDefault: address.isDefault
  })
  showDialog.value = true
}

// 删除地址
const handleDelete = (address) => {
  ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteAddress(address.id)
    initData()
    ElMessage.success('删除成功')
  })
}

// 提交表单
const handleSubmit =async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await addOrUpdateAddress(addressForm)
        ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
        showDialog.value = false
        initData()
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}
</script>

<style scoped>
.address-card {
  transition: all 0.3s ease;
}

/* 移动端优化 */
@media (max-width: 640px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 50px auto !important;
  }

  :deep(.el-overlay) {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  :deep(.el-dialog__body) {
    padding: 20px !important;
  }

  .address-form {
    padding: 0 !important;
  }
}

/* 添加这些样式以优化对话框滚动行为 */
:deep(.el-dialog) {
  margin: 0 auto;
  position: relative;
  display: flex;
  flex-direction: column;
  max-height: calc(100vh - 100px);
}

:deep(.el-dialog__body) {
  overflow-y: auto;
  max-height: calc(100vh - 250px);
}
</style>
